Page({
  data: {
    locations: ['请选择试驾地点', '北京', '上海', '广州', '深圳'],
    location: '请选择试驾地点',
    phone: '',
    agree: false,
  },

  onLoad(options) {},

  onLocationChange: function (e) {
    this.setData({
      location: this.data.locations[e.detail.value],
    });
  },

  onPhoneInput: function (e) {
    this.setData({
      phone: e.detail.value,
    });
  },

  onAgreeChange: function (e) {
    this.setData({
      agree: e.detail.value.includes('agree'),
    });
  },

  validateForm: function () {
    const { location, phone, agree } = this.data;

    if (location === '请选择试驾地点') {
      wx.showToast({
        title: '请选择试驾地点',
        icon: 'none',
      });
      return false;
    }

    if (!phone) {
      wx.showToast({
        title: '请输入手机号',
        icon: 'none',
      });
      return false;
    }

    if (!agree) {
      wx.showToast({
        title: '请同意隐私政策和用户协议',
        icon: 'none',
      });
      return false;
    }

    return true;
  },

  onSubmit: function () {
    if (this.validateForm()) {
      wx.request({
        url: 'http://1.94.51.11:8850/user/textDrive',
        method: 'POST',
        header: {
          Cookie: wx.getStorageSync('session'),
        },
        data: {
          position: this.data.location,
          phone: this.data.phone,
        },
        success: res => {
          wx.showToast({
            title: '预约成功',
            icon: res.message,
          });
        },
      });
    }
  },
});
